<template>
  <div class="fk_home">
    <div id="map" class="map"></div>
    <!-- 地图左侧 -->
    <transition name="el-fade-in-linear">
      <map-left
        class="map_left"
        v-if="isShowLeft"
        @handShowHospital="handShowHospital"
        @handleSurplus="handleSurplus"
        @sendDACRequestRes="receiveDACRequestRes"
        @showMedicalRoomEmit="handleShowMedicalRoomPoint"
        @showUserInfoEmit="handleShowUserInfo"
        @showAmbulanceEmit="handleShowAmbulance"
      ></map-left>
    </transition>
    <!-- 图例 -->
    <transition name="el-fade-in-linear">
      <div class="map_left_bottom" v-if="isShowLeft">
        <left-bottom @handleShowWhich="handleShowWhichPar" />
      </div>
    </transition>

    <!-- 地图右侧 -->
    <transition name="el-fade-in-linear">
      <div class="map_right">
        <map-right
          @getLinePosition="handleLinePosition"
          @clearLine="handleClearLine"
          @acceptPatientEmit="handleAceptPatient"
        />
      </div>
    </transition>
    <!-- 医院列表 -->
    <transition name="el-fade-in-linear">
      <div class="custom_dialog" v-if="isShowHospitalDialog">
        <hospital-info-dialog
          @closeHospitalEmit="handleCloseHospital"
          @hospitalNodeEmit="handleHospitalNode"
        >
        </hospital-info-dialog>
      </div>
    </transition>
    <!-- 医务室 -->
    <transition name="el-fade-in-linear">
      <div class="custom_dialog" v-if="isShowMedicalRoomDialog">
        <medical-room-dialog
          :data="medicalRoomDataTree"
          :medicalpointType="medicalpointType"
          @closeMedicalRoomPointEmit="handleCloseMedicalRoomPoint"
          @medicalRoomPointNodeEmit="handlemedicalRoomPointNodeClick"
        ></medical-room-dialog>
      </div>
    </transition>
    <!-- FOP医疗点 -->
    <transition name="el-fade-in-linear">
      <div class="custom_dialog" v-if="isShowFOPMedicalPonitDialog">
        <medical-room-dialog
          :data="FOPMedicalDataTree"
          :medicalpointType="medicalpointType"
          @closeMedicalRoomPointEmit="handleCloseMedicalRoomPoint"
          @medicalRoomPointNodeEmit="handlemedicalRoomPointNodeClick"
        ></medical-room-dialog>
      </div>
    </transition>
    <!-- 观众医疗点 -->
    <transition name="el-fade-in-linear">
      <div class="custom_dialog" v-if="isShowAudienceMedicalPonitDialog">
        <medical-room-dialog
          :data="audienceMedicalPointDataTree"
          :medicalpointType="medicalpointType"
          @closeMedicalRoomPointEmit="handleCloseMedicalRoomPoint"
          @medicalRoomPointNodeEmit="handlemedicalRoomPointNodeClick"
        ></medical-room-dialog>
      </div>
    </transition>
    <!-- 医生 -->
    <transition name="el-fade-in-linear">
      <div class="custom_dialog" v-if="isShowDoctorDialog">
        <user-info-dialog
          :data="doctorDataTree"
          :userType="userType"
          @closeUserInfoEmit="handleCloseUserInfo"
          @userInfoNodeEmit="handleUserInfoNodeClick"
        ></user-info-dialog>
      </div>
    </transition>
    <!-- 护士 -->
    <transition name="el-fade-in-linear">
      <div class="custom_dialog" v-if="isShowNurseDialog">
        <user-info-dialog
          :data="nurseDataTree"
          :userType="userType"
          @closeUserInfoEmit="handleCloseUserInfo"
          @userInfoNodeEmit="handleUserInfoNodeClick"
        ></user-info-dialog>
      </div>
    </transition>
    <!-- 车辆 -->
    <transition name="el-fade-in-linear">
      <div class="custom_dialog" v-if="isShowAmbulanceDialog">
        <ambulance-info-dialog
          :data="ambulanceDataTree"
          @closeAmbulanceInfoEmit="handleCloseAmbulanceInfo"
          @ambulanceInfoNodeEmit="handleAmbulanceInfoNode"
        ></ambulance-info-dialog>
      </div>
    </transition>
    <!-- 药品药材不足的医疗点列表 -->
    <transition name="el-fade-in-linear">
      <div class="custom_dialog" v-if="isShowDrugConsumDialog">
        <drug-consum-dialog
          :data="DACInsufficientTree"
          @closeDrugConsumEmit="closeDrugConsumClick"
          @drugconsumNodeEmit="handleDrugNodeClick"
        ></drug-consum-dialog>
      </div>
    </transition>
    <!-- 地图右侧按钮子弹窗 -->
    <transition name="el-fade-in-linear">
      <div class="show_dialog">
        <e-m-record />
        <regulation-measure />
        <emergency-plan />
      </div>
    </transition>
    <!-- 地图右侧 接诊病人自定义弹窗 -->
    <transition name="el-fade-in-linear">
      <div class="patient-custom-dialog" v-if="isShowAcceptPatient">
        <el-dialog
          v-model="isShowAcceptPatient"
          title="接诊病人列表"
          width="70%"
          align-center
        >
          <accept-patient :data="acceptPatientData"></accept-patient>
        </el-dialog>
      </div>
    </transition>
    <!-- 地图右侧 送往医院自定义弹窗 -->
    <transition name="el-fade-in-linear">
      <div class="patient-custom-dialog" v-if="isShowSendHospital">
        <send-hospital
          :data="sendHospitalData"
          @closeSendHospitalEmit="handleCloseSendHospital"
        ></send-hospital>
      </div>
    </transition>
    <!-- 场馆中按钮子弹窗 -->
    <!-- 赛程弹窗组件 -->
    <game-schedule></game-schedule>
    <!-- 医疗点弹窗组件 -->
    <medical-group
      :showMedicalGroupFlag="showMedicalGroupFlag"
      :doctorData="doctorData"
      :nurseData="nurseData"
    ></medical-group>
    <!-- 场馆车辆弹窗组件 -->
    <venue-ambu
      :showVenueAmbuFlag="showVenueAmbuFlag"
      :venueAmbuData="venueAmbuData"
    ></venue-ambu>
    <!-- 场馆药品耗材弹窗组件 -->
    <venue-grugs
      :showDrugFlag="showDrugFlag"
      :DACTableData="DACTableData"
    ></venue-grugs>

    <!-- 控制先隐藏按钮 -->
    <el-button
      type=""
      plain
      @click="handleShowLeft"
      style="position: absolute; bottom: 5px; left: 700px"
    >
      <template #icon>
        <el-icon>
          <Hide v-if="!isShowLeft" />
          <View v-else />
        </el-icon>
      </template>
      <span>左侧栏</span>
    </el-button>

    <el-button
      title="清除地图上的车辆标签图层"
      type=""
      plain
      @click="handleHideAmbuTag"
      style="position: absolute; bottom: 5px; left: 800px"
    >
      <template #icon>
        <el-icon>
          <DeleteFilled />
        </el-icon>
      </template>
      <span>车标签</span>
    </el-button>
    <el-button
      type=""
      plain
      @click="handleOrdinaryPattern"
      style="position: absolute; bottom: 5px; left: 900px"
    >
      <span>普通模式</span>
    </el-button>
    <!-- <el-button type="" plain @click="handleDiurnalPattern" style="position: absolute; bottom: 5px; left: 1000px;">
      <span>白天模式</span>
    </el-button> -->
    <el-button
      type=""
      plain
      @click="handleDarkPattern"
      style="position: absolute; bottom: 5px; left: 1000px"
    >
      <span>黑夜模式</span>
    </el-button>
  </div>
</template>

<script>
import BMapGL from 'BMapGL';
import {
  reactive,
  toRefs,
  onBeforeMount,
  onMounted,
  ref,
  watch,
  onUnmounted,
} from 'vue';
import { useStore } from 'vuex';
// 全局事件
import VueEvent from '../../utils/event';
// network
import { GetHospitalInfo } from '../../network/hospital';
import {
  GetActiVenueInfo,
  GetActiVenueDetail,
  GetMatchingVenues,
} from '../../network/venues';
import { GetAmbulanceInfo } from '../../network/ambulance';
import {
  GetMedicalPointPerson,
  GetAmbList,
  GetDACList,
  GetInsufficient,
  QueryMedicalPointUserList,
} from '../../network/hosVenAmbuListData';
// 图标弹窗
import {
  hospitalInfoContentcopy,
  venueContentcopy,
  vehicleInfoContentcopy,
  venueMedicalPointContentcopy,
} from './mapIconInfojs/mapIconInfousing';
// 场馆子弹窗
import GameSchedule from '../dialog/GameSchedule.vue';
import MedicalGroup from '../dialog/MedicalGroup.vue';
import VenueAmbu from '../dialog/VenueAmbu.vue';
import VenueGrugs from '../dialog/VenueGrugs.vue';
// 地图左侧栏
import MapLeft from './component/MapLeft.vue';
// 地图右侧栏
import MapRight from './component/MapRight.vue';
// 地图右侧按钮弹窗
import EMRecord from '../dialog/EMRecord.vue';
import RegulationMeasure from '../dialog/RegulationMeasure.vue';
import EmergencyPlan from '../dialog/EmergencyPlan.vue';
// 图例
import LeftBottom from './component/LeftBottom.vue';
// 自定义vuex 方法
import { setupMapState } from '../../store/utils/hook';
// 创建图标方法
import { CreateMark } from './methods/creatMarks';
// 转换经纬度
import { wgs84togcj02tobd09 } from '../../utils/84tobaiduGPS';

import { treeFormatData } from '../../modelUtils/returnModel';

import { ElMessage } from 'element-plus';
import { QueryPowerMarkLine } from '../../network/poyline';

import MedicalRoomDialog from './customDialog/MedicalRoomDialog.vue';
import UserInfoDialog from './customDialog/UserInfoDialog.vue';
import AmbulanceInfoDialog from './customDialog/AmbulanceInfoDialog.vue';
import HospitalInfoDialog from './customDialog/HospitalInfoDialog.vue';
import DrugConsumDialog from './customDialog/DrugConsumDialog.vue';

import SendHospital from '../map/component/compChildMessage/SendHospital.vue';
import AcceptPatient from '../map/component/compChildMessage/AcceptPatient.vue';
import { styleJson1, styleJson2 } from './mapstyleJson/index';
export default {
  name: 'homeMapchanging',
  components: {
    GameSchedule,
    MedicalGroup,
    VenueAmbu,
    VenueGrugs,
    MapLeft,
    LeftBottom,
    MapRight,
    EMRecord,
    RegulationMeasure,
    EmergencyPlan,
    MedicalRoomDialog,
    UserInfoDialog,
    AmbulanceInfoDialog,
    HospitalInfoDialog,
    DrugConsumDialog,
    SendHospital,
    AcceptPatient,
  },
  props: [],
  beforeRouteEnter(to, from, next) {
    // console.log(to, from, next)
    next((vm) => {
      // console.log(vm.$store)
      try {
      } catch (error) {}
    });
  },
  setup() {
    //定义地图
    var map = null;
    // 实例化管理仓储
    const store = useStore();
    // console.log(store)
    // 组件内部响应式状态
    const compState = reactive({
      ambuList: [],
      markerList: [],
      // 场馆医疗点
      showMedicalGroupFlag: 1,
      venuePersonType: [{ venDoctor: '5', venNurse: '6' }],
      doctorData: [],
      nurseData: [],
      // 场馆车辆
      showVenueAmbuFlag: 1,
      venueAmbuData: [],
      // 场馆药品耗材
      showDrugFlag: 1,
      drugConsumType: [{ drug: 1, consum: 2 }],
      DACTableData: [],
      // 医院
      isShowHospitalDialog: false,
      // 药品耗材
      isShowDrugConsumDialog: false,
      DACInsufficientTree: [],
      // 医务室/医疗点数据
      medicalRoomDataTree: [],
      // FOP医疗点数据
      FOPMedicalDataTree: [],
      // 观众医疗点数据
      audienceMedicalPointDataTree: [],
      // 医生数据
      doctorDataTree: [],
      // 护士数据
      nurseDataTree: [],
      // 车辆数据
      ambulanceDataTree: [],
      // 医疗点类型
      medicalpointType: '',
      // 人员类型
      userType: 0,
      // 医务室显示
      isShowMedicalRoomDialog: false,
      // FOP医疗点显示
      isShowFOPMedicalPonitDialog: false,
      // 观众医疗点显示
      isShowAudienceMedicalPonitDialog: false,
      // 医生显示
      isShowDoctorDialog: false,
      // 护士显示
      isShowNurseDialog: false,
      // 车辆显示
      isShowAmbulanceDialog: false,
      // 接收病人
      isShowSendHospital: false,
      sendHospitalData: [],
      isShowAcceptPatient: false,
      acceptPatientData: [],

      // 图例
      isShowLeft: true,
      // 定时器
      ambuTimer: null,
      // 两点之间的路线
      drivingLine: null,
      // 正在比赛的场馆
      venueView: [],

      // 车辆位置突出显示
      venueAmbu: [],
      ambuLayer: null,
      viewambu: null,
      layerdata: [],
      isShowVenueLayers: false,
    });
    // 取store数据
    const { ACVCodesVx } = setupMapState('app', ['ACVCodesVx']);
    // 车辆列表
    const { ambulanceTreeRemoteVx } = setupMapState('HospVenuAmbuModule', [
      'ambulanceTreeRemoteVx',
    ]);
    // 创建场馆下的医疗点
    const { venueMedicalPointArrVx } = setupMapState('HospVenuAmbuModule', [
      'venueMedicalPointArrVx',
    ]);
    // 医务室
    const { medicalRooms } = setupMapState('HospVenuAmbuModule', [
      'medicalRooms',
    ]);
    // 人员
    const { doctorsVx } = setupMapState('HospVenuAmbuModule', ['doctorsVx']);
    const { nursesVx } = setupMapState('HospVenuAmbuModule', ['nursesVx']);
    // 车辆
    const { ambulancesVx } = setupMapState('HospVenuAmbuModule', [
      'ambulancesVx',
    ]);
    // 接诊病人
    const { acceptPatientVx } = setupMapState('HospVenuAmbuModule', [
      'acceptPatientVx',
    ]);
    // 选择的场馆城市信息
    const { cityInfoVx } = setupMapState('HospVenuAmbuModule', ['cityInfoVx']);
    const { venueInfoVx } = setupMapState('HospVenuAmbuModule', [
      'venueInfoVx',
    ]);
    /**
     * 事件处理方法
     * */
    // 1.初始化地图方法
    const InitMyMap = (toMapCity) => {
      // console.log(map)
      map = new BMapGL.Map('map'); // 创建地图实例
      // map.centerAndZoom(new BMapGL.Point(120.214465, 30.254098), 12); // 初始化地图，设置中心点坐标和地图级别
      map.centerAndZoom(toMapCity, 12); // 初始化地图，设置中心点坐标和地图级别
      map.enableScrollWheelZoom(true); //开启鼠标滚轮缩放
      map.setHeading(30); //设置地图旋转角度
      var opts3D = {
        anchor: BMAP_ANCHOR_BOTTOM_LEFT,
        offset: new BMapGL.Size(10, 160),
      };
      var navi3DCtrl = new BMapGL.NavigationControl3D(opts3D); // 添加3D控件
      map.addControl(navi3DCtrl);
      map.addControl(
        new BMapGL.MapTypeControl({
          anchor: BMAP_ANCHOR_BOTTOM_LEFT,
          offset: new BMapGL.Size(10, 60),
        }),
      );

      // //监听地图点击
      // map.addEventListener('click', function (e) {
      //   // alert("点击的经纬度：" + e.latlng.lng + ", " + e.latlng.lat);
      //   // getAndSetCurCity(map);
      // });
      // // 监听地图缩放级别
      // map.addEventListener('zoomstart', function (e) {
      //   console.log(map.getZoom());
      //   createPoyline()
      // });
    };
    // 过滤节点数据
    const filterNode = (value, data) => {
      if (!value) return true;
      return data.name.includes(value);
    };
    // 清除mapvgl图层
    const handleRemoveLayers = (view) => {
      // console.log(view)
      if (view != null) view.removeAllLayers();
    };
    // 创建路线方法
    const startLuXian = (pathParams) => {
      let path = [];
      let lushu = null;
      let starPoint = null;
      let endPoint = null;
      starPoint = new BMapGL.Point(pathParams.ambLng, pathParams.ambLat);
      endPoint = new BMapGL.Point(pathParams.hosLng, pathParams.hosLat);
      path.push(starPoint);
      path.push(endPoint);
      // console.log(path);
      compState.drivingLine = new BMapGL.DrivingRoute(map, {
        renderOptions: { map: map, autoViewport: true },
      });
      // console.log(starPoint, endPoint);
      compState.drivingLine.search(starPoint, endPoint);
      map.centerAndZoom(starPoint, 16);
    };
    //********************** 左侧栏医院操作*/
    // 点击显示医院列表
    const handShowHospital = () => {
      // 关闭其他
      handleCloseMedicalRoomPoint({ type: compState.medicalpointType });
      handleCloseUserInfo({ type: compState.userType });
      handleCloseAmbulanceInfo();
      closeDrugConsumClick();
      // 显示
      compState.isShowHospitalDialog = true;
    };
    // 点击医院跳转
    const handleHospitalNode = (node) => {
      console.log('医院节点', node);
      map.flyTo(new BMapGL.Point(node.lng, node.lat), 17);
    };
    // 关闭定点医院信息列表
    const handleCloseHospital = () => {
      compState.isShowHospitalDialog = false;
    };
    //********************** 左侧栏药品耗材操作*/
    // 点击显示药品耗材医疗点列表
    const handleSurplus = (val) => {
      // console.log(val)
      handleCloseMedicalRoomPoint({ type: compState.medicalpointType });
      handleCloseUserInfo({ type: compState.userType });
      handleCloseAmbulanceInfo();
      handleCloseHospital();
      // 显示
      compState.isShowDrugConsumDialog = val;
    };
    // 点击医疗点节点
    const handleDrugNodeClick = async (node) => {
      // console.log(node)
      let medicalId = node.id;
      let drugConsumList = [];
      let drugList = await GetInsufficient({ mpCode: medicalId, type: 1 });
      // console.log("1", drugList);
      if (drugList.length > 0) {
        for (let i = 0; i < drugList.length; i++) {
          drugConsumList.push(drugList[i]);
        }
      }
      let consumList = await GetInsufficient({ mpCode: medicalId, type: 2 });
      // console.log("2", consumList);
      if (consumList.length > 0) {
        for (let j = 0; j < consumList.length; j++) {
          drugConsumList.push(consumList[j]);
        }
      }
      // console.log("3", drugConsumList);
      if (drugConsumList.length > 0) {
        drugConsumList.forEach((item) => {
          item.percentage = item.percentage + '%';
        });
      }
      compState.DACTableData = drugConsumList;
      compState.showDrugFlag++;
    };
    // 关闭医疗点列表
    const closeDrugConsumClick = () => {
      compState.isShowDrugConsumDialog = false;
    };
    //********************** 左侧栏医务室/医疗点操作*/
    const handleShowMedicalRoomPoint = (val) => {
      let { type } = val;
      // 赋值传给子组件
      compState.medicalpointType = type;
      // 关闭其他弹窗
      handleCloseHospital();
      handleCloseUserInfo(compState.userType);
      handleCloseAmbulanceInfo();
      closeDrugConsumClick();
      if (type == 'MedicalPointType-1') {
        //场馆医务室
        compState.isShowFOPMedicalPonitDialog = false;
        compState.isShowAudienceMedicalPonitDialog = false;
        // 显示
        // compState.medicalRoomDataTree = medicalRooms
        compState.isShowMedicalRoomDialog = true;
      } else if (type == 'MedicalPointType-2') {
        //FOP医疗点
        compState.isShowMedicalRoomDialog = false;
        compState.isShowAudienceMedicalPonitDialog = false;
        // 显示
        compState.isShowFOPMedicalPonitDialog = true;
      } else {
        //观众医疗点
        compState.isShowFOPMedicalPonitDialog = false;
        compState.isShowMedicalRoomDialog = false;
        // 显示
        compState.isShowAudienceMedicalPonitDialog = true;
      }
    };
    const handlemedicalRoomPointNodeClick = (node) => {
      console.log('医疗点节点');
      let LngLatObj = wgs84togcj02tobd09(node.Lng, node.Lat);
      map.flyTo(new BMapGL.Point(LngLatObj.Lng, LngLatObj.Lat), 19);
    };
    const handleCloseMedicalRoomPoint = ({ type }) => {
      if (type == 'MedicalPointType-1') {
        //场馆医务室
        compState.isShowMedicalRoomDialog = false;
      } else if (type == 'MedicalPointType-2') {
        //FOP医疗点
        compState.isShowFOPMedicalPonitDialog = false;
      } else {
        //观众医疗点
        compState.isShowAudienceMedicalPonitDialog = false;
      }
    };
    //********************** 左侧栏医生/护士点操作*/
    const handleShowUserInfo = ({ type }) => {
      // 赋值传给子组件
      compState.userType = type;
      // console.log(compState.userType)
      handleCloseMedicalRoomPoint({ type: compState.medicalpointType });
      handleCloseAmbulanceInfo();
      handleCloseHospital();
      closeDrugConsumClick();
      if (type == 5) {
        //医生
        compState.isShowNurseDialog = false;
        // 显示
        // compState.doctorDataTree = doctorsVx
        compState.isShowDoctorDialog = true;
      } else {
        //护士
        compState.isShowDoctorDialog = false;
        // 显示
        // compState.nurseDataTree = nursesVx
        compState.isShowNurseDialog = true;
      }
    };
    const handleUserInfoNodeClick = (node) => {
      // 不做处理
      console.log('人员节点');
    };
    const handleCloseUserInfo = ({ type }) => {
      if (type == 5) {
        compState.isShowDoctorDialog = false;
      } else {
        compState.isShowNurseDialog = false;
      }
    };
    //********************** 左侧栏车辆操作*/
    const handleShowAmbulance = async (payload) => {
      // 关闭其他
      handleCloseMedicalRoomPoint({ type: compState.medicalpointType });
      handleCloseUserInfo({ type: compState.userType });
      handleCloseHospital();
      closeDrugConsumClick();
      // console.log(payload)
      // 显示
      compState.isShowAmbulanceDialog = true;
      // compState.ambulanceDataTree = ambulancesVx
    };
    const handleAmbulanceInfoNode = (node) => {
      console.log('车辆节点');
      // console.log(node)
      let LngLatObj = wgs84togcj02tobd09(node.Lng, node.Lat);
      map.flyTo(new BMapGL.Point(LngLatObj.Lng, LngLatObj.Lat), 19);
    };
    const handleCloseAmbulanceInfo = () => {
      compState.isShowAmbulanceDialog = false;
    };

    //**********************  接诊和送往*/
    const handleAceptPatient = () => {
      store.dispatch('HospVenuAmbuModule/getAcceptPatient');
      compState.acceptPatientData = acceptPatientVx;
      compState.isShowAcceptPatient = true;
    };
    // const handleCloseAcceptPatient = () => {
    //   compState.isShowAcceptPatient = false
    // }
    const handleSendHospital = () => {
      console.log('送往医院');

      state.sendHospitalData = [
        {
          name: 'sendHospitalData',
        },
      ];
      // state.isShowSendHospital = true
    };
    const handleCloseSendHospital = () => {
      state.isShowSendHospital = false;
    };
    // 药品耗材tree
    const receiveDACRequestRes = (data) => {
      // console.log("药品耗材tree", data)
      compState.DACInsufficientTree = treeFormatData(data);
    };

    //********************** 左侧栏图例显隐藏 */
    const handleShowWhichPar = (val) => {
      // 显示哪类图标
      // console.log(val)
      // console.log(map.getOverlays())
      // 获取地图上的图标
      let overlays = map.getOverlays().filter((item) => {
        return (
          item.clas == 'hospital' ||
          item.clas == 'venue' ||
          item.clas == 'taskvehicle' ||
          item.clas == 'onvehicle' ||
          item.clas == 'notaskvehicle' ||
          item.clas == 'venueMedicalPoint'
        );
      });
      // console.log("所有图标", overlays)

      if (val.length > 0) {
        let showArr = [];
        let hideArr = [];
        // 取要显示的图标(根据flag)
        val.forEach((valItem) => {
          let showIcons = overlays.filter((overlaysItem) => {
            return valItem.flag == overlaysItem.clas;
          });
          showArr.push(...showIcons);
        });
        // 取隐藏的图标(根据项)
        hideArr = overlays.filter((overlaysItem) => {
          return showArr.indexOf(overlaysItem) === -1;
        });
        // console.log("显示的图标：", showArr, "隐藏的图标：", hideArr)
        // 处理隐藏和显示
        showArr.forEach((item) => {
          item.show();
        });
        hideArr.forEach((item) => {
          item.hide();
        });
      } else {
        // console.log("隐藏所有图标")
        overlays.forEach((item) => {
          item.hide();
        });
      }
    };

    //********************** 右侧栏*/
    // 查看线路
    const handleLinePosition = (data) => {
      // console.log(data);
      if (compState.drivingLine == null) {
        startLuXian(data);
      } else {
        compState.drivingLine.clearResults();
        startLuXian(data);
      }
    };
    // 清除线路
    const handleClearLine = (data) => {
      if (data && compState.drivingLine != null) {
        compState.drivingLine.clearResults();
      }
    };

    // 左侧显隐藏按钮
    const handleShowLeft = () => {
      compState.isShowLeft = !compState.isShowLeft;
      handleCloseMedicalRoomPoint({ type: compState.medicalpointType });
      handleCloseUserInfo({ type: compState.userType });
      handleCloseHospital();
      handleCloseAmbulanceInfo();
    };
    // 车标签图层隐藏按钮
    const handleHideAmbuTag = () => {
      handleRemoveLayers(compState.viewambu);
      compState.isShowVenueLayers = false;
    };
    //********************** 创建两点之间直线线路 （之后要改）*/
    const createPoylineItem = (param, arr, map, color) => {
      param.forEach((item, index) => {
        // console.log(item['Lng'])
        arr.push(new BMapGL.Point(item['Lng'], item['Lat']));
      });
      var polyline = new BMapGL.Polyline(arr, {
        strokeColor: color,
        strokeWeight: 5,
        strokeOpacity: 1,
      }); //创建折线
      map.addOverlay(polyline);
    };
    const createPoylineItemFun = (
      param,
      map,
      color,
      strokeWeight,
      strokeOpacity,
      strokeStyle,
    ) => {
      // console.log(param)
      let arr = [];
      param.forEach((item, index) => {
        // console.log(item['Lng'])
        arr.push(new BMapGL.Point(item['lng'], item['lat']));
      });
      var polyline = new BMapGL.Polyline(arr, {
        strokeColor: color,
        strokeWeight: strokeWeight,
        strokeOpacity: strokeOpacity,
        strokeStyle: strokeStyle,
      }); //创建折线
      map.addOverlay(polyline);
    };
    // 创建多点线路
    const createPoyline = (map) => {
      let pointArr = require('./statictestline.json');
      let swimArr = require('./lineJson/swim.json');
      let runArr = require('./lineJson/run.json');
      let bicycleArrs = require('./lineJson/bicycle.json');
      let aa = pointArr.aa;
      let bb = pointArr.bb;
      // console.log(pointArr)
      // let polylineArr1 = []
      // let polylineArr2 = []
      // let polylineArr3 = []
      // let polylineArr4 = []
      // let polylineArr5 = []
      // let polylineArr6 = []
      // let polylineArr7 = []
      // let polylineArr8 = []
      // let polylineArr9 = []
      // createPoylineItem(aa, polylineArr1, map)
      // createPoylineItem(bb, polylineArr2, map)
      // createPoylineItem(pointArr.cc, polylineArr3, map)
      // createPoylineItem(pointArr.dd, polylineArr4, map)
      // createPoylineItem(pointArr.ee, polylineArr5, map)
      // createPoylineItem(pointArr.ff, polylineArr6, map)
      // createPoylineItem(pointArr.gg, polylineArr7, map)
      // createPoylineItem(pointArr.hh, polylineArr8, map)
      // createPoylineItem(pointArr.ii, polylineArr9, map)

      // 游泳
      let swimPolylineArr = [];
      createPoylineItem(swimArr.arr, swimPolylineArr, map, '#e6a23c');
      // 跑步
      let runPolylineArr = [];
      createPoylineItem(runArr.arr, runPolylineArr, map, '#67c23a');
      // 自行车
      let bicyclePolylineArr1 = [];
      let bicyclePolylineArr2 = [];
      let bicyclePolylineArr3 = [];
      let bicyclePolylineArr4 = [];
      createPoylineItem(bicycleArrs.arr1, bicyclePolylineArr1, map, '#f56c6c');
      createPoylineItem(bicycleArrs.arr2, bicyclePolylineArr2, map, '#f56c6c');
      createPoylineItem(bicycleArrs.arr3, bicyclePolylineArr3, map, '#f56c6c');
      createPoylineItem(bicycleArrs.arr4, bicyclePolylineArr4, map, '#f56c6c');
    };
    // 地图模式
    const handleOrdinaryPattern = () => {
      map.setMapStyleV2({
        styleJson: {},
      });
    };
    const handleDiurnalPattern = () => {
      map.setMapStyleV2({
        styleJson: styleJson1,
      });
    };
    const handleDarkPattern = () => {
      map.setMapStyleV2({
        styleJson: styleJson2,
      });
    };
    /**
     * 工具方法
     * 定时器
     */
    // 延时器
    const sleep = (ms) => {
      return new Promise((resolve) => {
        setTimeout(resolve, ms);
      });
    };

    // 组件挂载前
    onBeforeMount(() => {});
    // 组件挂载后
    onMounted(() => {
      // 获取当前城市
      let toMapCity =
        store.state.app.cityNameVx != ''
          ? store.state.app.cityNameVx
          : '杭州市';
      //自定义图标
      var taskVehicleIconUrl = require('../../assets/imgHome/mapIcon/task-vehicle.png'); //任务小车图标
      var ontaskVehicleIconUrl = require('../../assets/imgHome/mapIcon/on-vehicle.png'); // 待命小车图标
      var notaskVehicleIconUrl = require('../../assets/imgHome/mapIcon/notask-vehicle.png'); // 暂停车图标
      var hospitalIconUrl = require('../../assets/imgHome/mapIcon/hospital.png'); //医院图标
      var venueIconUrl = require('../../assets/imgHome/mapIcon/venue.png'); //场馆图标
      var venueMedicalPointIconUrl = require('../../assets/imgHome/mapIcon/医疗点-1.png'); //场馆内医疗点图标
      var venueMedicalPointIconUrl_noLine = require('../../assets/imgHome/mapIcon/医疗点-灰1.png');
      // 初始化地图
      InitMyMap(toMapCity);
      // 创建静态线路
      createPoyline(map);

      // 之前地图加载不出来的异常的处理
      // await sleep(1500)

      /**
       * 监听map.centerAndZoom()方法的执行
       */
      map.addEventListener('load', async function (e) {
        console.log('map load');
        // console.log(ACVCodesVx.value)
        let param = ACVCodesVx.value;
        // console.log(param)
        try {
          // 医院数据及图标创建-----------------------------------------------start
          GetHospitalInfo(param)
            .then((res) => {
              // console.log(res)
              if (res && res.length != 0) {
                store.dispatch('HospVenuAmbuModule/saveHospitalAct', res);
                res.forEach((item) => {
                  // console.log(item)
                  // 转换经纬度
                  let LngLatObj = wgs84togcj02tobd09(item.Lng, item.Lat);
                  let marker = CreateMark(
                    hospitalIconUrl,
                    35,
                    35,
                    LngLatObj.Lng,
                    LngLatObj.Lat,
                    'hospital',
                    item.Code,
                  );
                  // 图标存进数组
                  compState.markerList.push(marker);
                  // 监听图标点击
                  marker.addEventListener('click', function () {
                    // console.log(marker)
                    var hospid = marker.id;
                    // 根据id找到此医院
                    let curMark = res.filter((item) => {
                      return item.Code == hospid;
                    });
                    // 设置中心点坐标和地图级别
                    map.flyTo(
                      new BMapGL.Point(LngLatObj.Lng, LngLatObj.Lat),
                      18,
                    );
                    // console.log(curMark[0])
                    let opts = {
                      title: '医院信息',
                      width: 270,
                      height: 'auto',
                    };
                    let myinfoWindow = new BMapGL.InfoWindow(
                      hospitalInfoContentcopy(curMark[0]),
                      opts,
                    );
                    this.openInfoWindow(myinfoWindow);
                  });
                  // 1s后将医院图标添加到地图
                  let timer = setTimeout(() => {
                    map.addOverlay(marker);
                    clearTimeout(timer);
                  }, 500);
                });
              } else {
                console.log('homeMap/GetHospitalInfo', '医院数据返回为空');
              }
            })
            .catch((err) => {
              console.log('homeMap/GetHospitalInfo', err);
            });
          // ---------------------------------------------------------------end
          // 车辆数据及图标创建-----------------------------------------------start
          GetAmbulanceInfo(param)
            .then((res) => {
              // console.log(res)
              if (res && res.length != 0) {
                store.dispatch('HospVenuAmbuModule/saveAmbulanceAct', res);
                // 将车辆返回结果赋值给响应式对象
                compState.ambuList = res;
                compState.ambuList.forEach((item) => {
                  // 转换经纬度
                  let LngLatObj = wgs84togcj02tobd09(item.Lng, item.Lat);
                  // 根据任务状态判断
                  switch (item.StateCode) {
                    // 任务中
                    case 0:
                    case 1:
                    case 2:
                    case 3:
                    case 4:
                    case 5:
                    case 101:
                    case 102:
                      // console.log(item);
                      let marker1 = CreateMark(
                        taskVehicleIconUrl,
                        35,
                        35,
                        LngLatObj.Lng,
                        LngLatObj.Lat,
                        'taskvehicle',
                        item.Code,
                        item.Name,
                        item.Direction,
                      );
                      compState.markerList.push(marker1);
                      marker1.addEventListener('click', function () {
                        // console.log(marker1)
                        var vehicleid = marker1.id;
                        // 根据id找到此车辆
                        let ambuCurMark = compState.ambuList.filter(
                          (item, index) => {
                            return item.Code == vehicleid;
                          },
                        );
                        // 设置中心点坐标和地图级别
                        map.flyTo(
                          new BMapGL.Point(LngLatObj.Lng, LngLatObj.Lat),
                          20,
                        );
                        // console.log(ambuCurMark[0])
                        let opts = {
                          title: '车辆信息',
                          width: 270,
                          height: 'auto',
                        };
                        let ambuInfoWindow = new BMapGL.InfoWindow(
                          vehicleInfoContentcopy(ambuCurMark[0]),
                          opts,
                        );
                        marker1.openInfoWindow(ambuInfoWindow);
                      });
                      // 1s后将车辆图标添加到地图
                      let timer1 = setTimeout(() => {
                        map.addOverlay(marker1);
                        clearTimeout(timer1);
                      }, 700);
                      break;
                    // 待命中
                    case 6:
                    case 7:
                      let marker2 = CreateMark(
                        ontaskVehicleIconUrl,
                        35,
                        35,
                        LngLatObj.Lng,
                        LngLatObj.Lat,
                        'onvehicle',
                        item.Code,
                        item.Name,
                        item.Direction,
                      );
                      compState.markerList.push(marker2);
                      marker2.addEventListener('click', function () {
                        // console.log(marker2)
                        var vehicleid = marker2.id;
                        // 根据id找到此车辆
                        let ambuCurMark = compState.ambuList.filter(
                          (item, index) => {
                            return item.Code == vehicleid;
                          },
                        );
                        // 设置中心点坐标和地图级别
                        map.flyTo(
                          new BMapGL.Point(LngLatObj.Lng, LngLatObj.Lat),
                          20,
                        );
                        // console.log(ambuCurMark[0])
                        let opts = {
                          title: '车辆信息',
                          width: 270,
                          height: 'auto',
                        };
                        let ambuInfoWindow = new BMapGL.InfoWindow(
                          vehicleInfoContentcopy(ambuCurMark[0]),
                          opts,
                        );
                        marker2.openInfoWindow(ambuInfoWindow);
                      });
                      let timer2 = setTimeout(() => {
                        map.addOverlay(marker2);
                        clearTimeout(timer2);
                      }, 700);
                      break;
                    // 暂停调用
                    case 8:
                    case 9:
                      let marker3 = CreateMark(
                        notaskVehicleIconUrl,
                        17.5,
                        35,
                        LngLatObj.Lng,
                        LngLatObj.Lat,
                        'notaskvehicle',
                        item.Code,
                        item.Name,
                        item.Direction,
                      );
                      compState.markerList.push(marker3);
                      marker3.addEventListener('click', function () {
                        // console.log(marker3)
                        var vehicleid = marker3.id;
                        // 根据id找到此车辆
                        let ambuCurMark = compState.ambuList.filter(
                          (item, index) => {
                            return item.Code == vehicleid;
                          },
                        );
                        // 设置中心点坐标和地图级别
                        map.flyTo(
                          new BMapGL.Point(LngLatObj.Lng, LngLatObj.Lat),
                          20,
                        );
                        // console.log(ambuCurMark[0])
                        let opts = {
                          title: '车辆信息',
                          width: 270,
                          height: 'auto',
                        };
                        let ambuInfoWindow = new BMapGL.InfoWindow(
                          vehicleInfoContentcopy(ambuCurMark[0]),
                          opts,
                        );
                        marker3.openInfoWindow(ambuInfoWindow);
                      });
                      let timer3 = setTimeout(() => {
                        map.addOverlay(marker3);
                        clearTimeout(timer3);
                      }, 700);
                      break;
                    default:
                      break;
                  }
                });
              } else {
                console.log('homeMap/GetAmbulanceInfo', '车辆数据返回为空');
              }
            })
            .catch((err) => {
              console.log(err);
            });
          // -----------------------------------------------------------------end
          //获取正在举行的场馆并在地图标注---------------------------------------start
          GetMatchingVenues(param)
            .then((res) => {
              // console.log(res);
              // 存正在比赛场馆的经纬度
              var lngAndLats = [];
              if (res.length > 0) {
                res.forEach((item) => {
                  lngAndLats.push({ lng: item.Lng, lat: item.Lat });
                });
                compState.venueView = new mapvgl.View({
                  map: map,
                });
                var colors = ['#f00', '#ff0', '#0ff', '#00f'];
                var data = lngAndLats.map((item, index) => {
                  let newItem = wgs84togcj02tobd09(item.lng, item.lat);
                  // console.log(newItem);
                  return {
                    geometry: {
                      type: 'Point',
                      coordinates: [newItem.Lng, newItem.Lat],
                    },
                    color: colors[0],
                    // 圆的半径
                    size: 5,
                  };
                });
                var bubbleLayer = new mapvgl.CircleLayer({
                  // 绘制带泡泡的圆
                  type: 'bubble',
                  size: (size) => 1 * size,
                  // 扩散半径，支持直接设置和回调两种形式，size为点的大小
                  radius(size) {
                    return 5 * size;
                  },
                  // 扩散时间
                  duration: 1,
                  // 渐隐时间
                  trail: 1,
                });
                compState.venueView.addLayer(bubbleLayer);
                bubbleLayer.setData(data);
              } else {
                console.log('没有正在举办比赛的场馆！');
              }
            })
            .catch((err) => {
              console.log('homeMap/GetMatchingVenues', err);
            });
          // ------------------------------------------------------------------end
          // 取poyline 绘制的线路并显示------------------------------------------start
          await QueryPowerMarkLine(param)
            .then((res) => {
              // console.log(res)
              if (res?.length > 0) {
                res.forEach((item) => {
                  let paramPath = JSON.parse(item.Path);
                  if (paramPath && paramPath.length > 0) {
                    createPoylineItemFun(
                      paramPath,
                      map,
                      item.Colour,
                      item.Width,
                      item.Pellucidity,
                      item.Pattern,
                    );
                  } else {
                    console.log('paramPath绘制的线路', 'paramPath 长度为0！');
                  }
                });
              }
            })
            .catch((err) => {
              console.log('homeMap/QueryPowerMarkLine', err);
            });
          // ------------------------------------------------------------------end
          // 场馆数据及图标创建--------------------------------------------------start
          await GetActiVenueInfo(param)
            .then((res) => {
              // console.log(res)
              if (res && res.length != 0) {
                store.dispatch('HospVenuAmbuModule/saveVenueAct', res);
                res.forEach((item) => {
                  // 转换经纬度
                  let LngLatObj = wgs84togcj02tobd09(item.Lng, item.Lat);
                  let marker = CreateMark(
                    venueIconUrl,
                    35,
                    35,
                    LngLatObj.Lng,
                    LngLatObj.Lat,
                    'venue',
                    item.Code,
                  );
                  // 图标存进数组
                  compState.markerList.push(marker);
                  // 监听图标点击
                  marker.addEventListener('click', async function () {
                    // console.log(marker)
                    var venueid = marker.id;
                    // 根据id找到此场馆
                    let curMark = res.filter((item, index) => {
                      return item.Code == venueid;
                    });
                    // 设置中心点坐标和地图级别
                    map.flyTo(
                      new BMapGL.Point(LngLatObj.Lng, LngLatObj.Lat),
                      18,
                    );
                    // console.log(curMark[0])
                    let opts = {
                      title: '场馆信息',
                      width: 400,
                      height: 'auto',
                    };

                    // 根据场馆id获取场馆详情
                    let venueDetail = await GetActiVenueDetail({
                      venuesCode: venueid,
                    });
                    // console.log(venueDetail)
                    if (venueDetail != null) {
                      await store.dispatch(
                        'HospVenuAmbuModule/saveVenueDetailAct',
                        venueDetail,
                      );
                    }
                    let myinfoWindow = new BMapGL.InfoWindow(
                      venueContentcopy({
                        curMark: curMark[0],
                        venueDetail: venueDetail,
                      }),
                      opts,
                    );
                    // 监听弹窗打开，再根据dom元素监听按钮点击
                    myinfoWindow.addEventListener('open', function () {
                      console.log('myinfoWindow is open');
                      // 在这里移除车辆图标图层
                      if (compState.viewambu != null) {
                        compState.viewambu.removeAllLayers();
                      }

                      // console.log(myinfoWindow.isOpen())
                      let gameScheduleDoc =
                        document.getElementById('gameScheduleClick');
                      let medicalGroupDoc =
                        document.getElementById('medicalGroupClick');
                      let ambulanceDoc =
                        document.getElementById('ambulanceClick');
                      let drugDoc = document.getElementById('drugClick');
                      let venueAmbulanceShowDoc = document.getElementById(
                        'venueAmbulanceShowClick',
                      );
                      // console.log(ambulanceDoc);
                      // 赛程按钮
                      if (gameScheduleDoc.id == 'gameScheduleClick') {
                        gameScheduleDoc.onclick = () => {
                          console.log('gameScheduleClick');
                          // console.log(venueid)
                          // 向弹窗发送事件
                          VueEvent.emit('showGameSchedule', {
                            isShowGameSchedule: true,
                            id: venueid,
                          });
                        };
                      }
                      // 医疗点按钮
                      if (medicalGroupDoc.id == 'medicalGroupClick') {
                        medicalGroupDoc.onclick = async () => {
                          console.log('medicalGroupClick');
                          // 获取场馆医疗点数据(医生，护士都取出来)
                          // console.log(venueid);
                          let medicalPointDoctor = await GetMedicalPointPerson({
                            venuesCode: venueid,
                            personType: compState.venuePersonType[0].venDoctor,
                          });
                          let medicalPointNurse = await GetMedicalPointPerson({
                            venuesCode: venueid,
                            personType: compState.venuePersonType[0].venNurse,
                          });
                          compState.doctorData = medicalPointDoctor;
                          compState.nurseData = medicalPointNurse;
                          // console.log('医生和护士', compState.doctorData, compState.nurseData)
                          compState.showMedicalGroupFlag++;
                        };
                      }
                      // 车辆按钮
                      if (ambulanceDoc.id == 'ambulanceClick') {
                        // 单击显示车辆列表
                        ambulanceDoc.onclick = async () => {
                          console.log('ambulanceClick');
                          // console.log(venueid)
                          let venueAmbulance = await GetAmbList({
                            venuesCode: venueid,
                          });
                          compState.venueAmbuData = venueAmbulance;
                          // console.log(compState.medicalPointAmbuData)
                          compState.showVenueAmbuFlag++;
                        };
                      }

                      // 车辆位置按钮(突出显示某场馆的车辆)
                      compState.viewambu = new mapvgl.View({
                        map: map,
                      });
                      compState.ambuLayer = new mapvgl.LabelLayer({
                        textAlign: 'center',
                        textColor: '#fc0',
                        borderColor: '#666',
                        backgroundColor: '#666',
                        padding: [2, 5],
                        borderRadius: 5,
                        fontSize: 12,
                        lineHeight: 16,
                        collides: true, // 是否开启碰撞检测, 数量较多时建议打开
                        enablePicked: true,
                        autoSelect: true,
                        onClick: (e) => {
                          // 点击事件
                          // console.log('click', e);
                        },
                      });

                      if (
                        venueAmbulanceShowDoc.id == 'venueAmbulanceShowClick'
                      ) {
                        venueAmbulanceShowDoc.onclick = async function () {
                          // 显示车辆标签图层
                          compState.isShowVenueLayers = true;
                          // console.log("venueAmbulanceShowClick");
                          // console.log(venueid)
                          compState.venueAmbu = await GetAmbList({
                            venuesCode: venueid,
                          });
                          // console.log(compState.venueAmbu)

                          // 地图显示车辆信息
                          // console.log(curMark[0])

                          compState.layerdata = [];
                          if (compState.venueAmbu.length > 0) {
                            compState.venueAmbu.forEach((item) => {
                              let newItem = wgs84togcj02tobd09(
                                item.Lng,
                                item.Lat,
                              );
                              compState.layerdata.push({
                                ambucode: item.Code,
                                venueName: curMark[0].CHIDescription,
                                geometry: {
                                  type: 'Point',
                                  coordinates: [newItem.Lng, newItem.Lat],
                                },
                                properties: {
                                  text:
                                    item.Name +
                                    '\n' +
                                    curMark[0].CHIDescription,
                                },
                              });
                            });

                            // mapvgl容器添加layer
                            compState.viewambu.addLayer(compState.ambuLayer);
                            // layer设置数据
                            compState.ambuLayer.setData(compState.layerdata);

                            ElMessage({
                              message:
                                '此场馆共有车辆' +
                                compState.venueAmbu.length +
                                '辆',
                              type: 'success',
                            });
                          } else {
                            console.log('此场馆无车辆！');
                            ElMessage({
                              message: '此场馆无车辆！',
                              type: 'warning',
                            });
                          }
                          map.centerAndZoom(
                            new BMapGL.Point(curMark[0].Lng, curMark[0].Lat),
                            12,
                          );
                        };
                      }
                      // 药品耗材按钮
                      if (drugDoc.id == 'drugClick') {
                        drugDoc.onclick = async () => {
                          console.log('drugClick');
                          // console.log(venueid)
                          var medicalPointDACArr = [];
                          let medicalPointDrug = await GetDACList({
                            venuesCode: venueid,
                            type: compState.drugConsumType[0].drug,
                          });
                          // console.log(medicalPointDrug);
                          if (medicalPointDrug.length > 0) {
                            medicalPointDrug.forEach((item) => {
                              medicalPointDACArr.push(item);
                            });
                          }

                          let medicalPointConsum = await GetDACList({
                            venuesCode: venueid,
                            type: compState.drugConsumType[0].consum,
                          });
                          if (medicalPointConsum.length > 0) {
                            medicalPointConsum.forEach((item) => {
                              medicalPointDACArr.push(item);
                            });
                          }
                          // console.log(medicalPointDACArr);
                          if (medicalPointDACArr.length > 0) {
                            medicalPointDACArr.forEach((item) => {
                              item.percentage = item.percentage + '%';
                            });
                          }
                          compState.DACTableData = medicalPointDACArr;
                          // console.log( state.DACTableData)
                          compState.showDrugFlag++;
                        };
                      }
                    });
                    // 信息窗口关闭的时候可以实时监听到
                    myinfoWindow.addEventListener('close', function () {
                      console.log(
                        'myinfoWindow',
                        'close',
                        myinfoWindow.isOpen(),
                      );
                      if (compState.viewambu != null) {
                        // compState.viewambu.removeAllLayers();
                      }
                    });
                    // 先进行事件监听 然后才打开图标弹窗********
                    marker.openInfoWindow(myinfoWindow);
                  });
                  // 1s后将场馆图标添加到地图
                  let timer = setTimeout(() => {
                    map.addOverlay(marker);
                    clearTimeout(timer);
                  }, 600);
                });
              } else {
                console.log('homeMap/GetActiVenueInfo', '场馆数据返回为空');
              }
            })
            .catch((err) => {
              console.log('homeMap/GetActiVenueInfo', err);
            });
          // ------------------------------------------------------------------end
          // 场馆下的医疗点图标创建 await必须加，不然venueMedicalPointArrVx为空---satrt
          // console.log(venueMedicalPointArrVx.value)
          let venueMedicalPointArr = venueMedicalPointArrVx.value;

          venueMedicalPointArr.forEach((item) => {
            // console.log(item)
            // 经纬度转换过了
            let color = '#9933ff';
            let iconUrl = venueMedicalPointIconUrl;
            if (item.online == false) {
              iconUrl = venueMedicalPointIconUrl_noLine;
              color = '#767676';
            } else {
              iconUrl = venueMedicalPointIconUrl;
              color = '#9933ff';
            }
            let marker = CreateMark(
              iconUrl,
              50,
              50,
              item.lng,
              item.lat,
              'venueMedicalPoint',
              item.id,
              item.name,
              undefined,
              color,
            );
            // 图标存进数组
            compState.markerList.push(marker);
            // 监听图标点击
            marker.addEventListener('click', async function () {
              // console.log(marker)
              var venueMedicalPointid = marker.id;
              let medicalInfo = {};
              await QueryMedicalPointUserList({
                medicalPointCode: venueMedicalPointid,
              })
                .then((res) => {
                  // console.log(res)
                  medicalInfo = res;
                })
                .catch((err) => {
                  console.log(err);
                });
              // 设置中心点坐标和地图级别
              map.flyTo(new BMapGL.Point(item.lng, item.lat), 20);
              let opts = {
                title: '医疗点信息',
                width: 270,
                height: 'auto',
              };
              let myinfoWindow = new BMapGL.InfoWindow(
                venueMedicalPointContentcopy(medicalInfo),
                opts,
              );
              this.openInfoWindow(myinfoWindow);
            });
            // 1s后将医院图标添加到地图
            let timer = setTimeout(() => {
              map.addOverlay(marker);
              clearTimeout(timer);
            }, 600);
          });
          // ------------------------------------------------------------------end
          // 8s定时循环刷新车辆位置及状态信息-------------------------------------start
          compState.ambuTimer = setInterval(() => {
            console.log('homeMap/open车辆循环刷新定时器！');
            // compState.ambuTimer = setTimeout(() => {
            // 获取地图上所有标注
            let mapOverlays = map.getOverlays();
            // console.log(mapOverlays)
            GetAmbulanceInfo(param)
              .then((res) => {
                // console.log(res)
                compState.ambuList = res;
                store.dispatch('HospVenuAmbuModule/saveAmbulanceAct', res);
                compState.ambulanceTreeRemote = ambulanceTreeRemoteVx.value;
                // 先获取图标中的车辆类型的标注
                let ambuMarkerArr = mapOverlays.filter((item) => {
                  // console.log(item.clas)
                  return (
                    item.clas == 'taskvehicle' ||
                    item.clas == 'onvehicle' ||
                    item.clas == 'notaskvehicle'
                  );
                });
                // console.log(ambuMarkerArr)

                ambuMarkerArr.forEach((makerItem) => {
                  compState.ambuList.forEach((item) => {
                    if (makerItem.id == item.Code) {
                      // 转换经纬度
                      let LngLatObj = wgs84togcj02tobd09(item.Lng, item.Lat);
                      // console.log(makerItem)
                      // 设置位置
                      makerItem.setPosition(
                        new BMapGL.Point(LngLatObj.Lng, LngLatObj.Lat),
                      );
                      // 设置旋转角度
                      makerItem.setRotation(item.Direction);
                      // 获取图标文本标注对象，方便设置样式
                      let label = makerItem.getLabel();
                      // 根据车辆状态设置车辆图标
                      switch (item.StateCode) {
                        // 任务中
                        case 0:
                        case 1:
                        case 2:
                        case 3:
                        case 4:
                        case 5:
                        case 101:
                        case 102:
                          makerItem.setIcon(
                            new BMapGL.Icon(
                              taskVehicleIconUrl,
                              new BMapGL.Size(35, 35),
                            ),
                          );
                          // console.log(makerItem.getLabel())
                          // 设置文本标注颜色
                          label.setStyle({ color: 'red' });
                          break;
                        // 待命中
                        case 6:
                        case 7:
                          makerItem.setIcon(
                            new BMapGL.Icon(
                              ontaskVehicleIconUrl,
                              new BMapGL.Size(35, 35),
                            ),
                          );
                          label.setStyle({ color: 'blue' });
                          break;
                        // 暂停调用
                        case 8:
                        case 9:
                          makerItem.setIcon(
                            new BMapGL.Icon(
                              notaskVehicleIconUrl,
                              new BMapGL.Size(17.5, 35),
                            ),
                          );
                          label.setStyle({ color: 'gray' });
                          break;
                        default:
                          break;
                      }
                    }
                  });
                });
                // 更新车辆标签图层
                // console.log(compState.isShowVenueLayers)
                // 当车辆标签图层存在数据并且显示时，定时器生效，刷新车辆
                if (compState.isShowVenueLayers) {
                  let ambulayerData = compState.ambuLayer.getData();
                  if (ambulayerData.length > 0) {
                    // 获取场馆名称
                    let venueName = ambulayerData[0].venueName;
                    //  console.log(venueName)
                    compState.layerdata = [];
                    // 遍历场馆下车辆(compState.venueAmbu是第一次点击缓存的数据，只要上面的if条件通过compState.venueAmbu不为空)
                    // res 是所有的车辆，根据车辆编码筛选某场馆的车辆
                    // console.log("场馆车辆：", compState.venueAmbu)
                    res.forEach((resItem) => {
                      compState.venueAmbu.forEach((item) => {
                        if (resItem.Code == item.Code) {
                          // console.log(item)
                          let newItem = wgs84togcj02tobd09(
                            resItem.Lng,
                            resItem.Lat,
                          );
                          compState.layerdata.push({
                            ambucode: item.Code,
                            venueName: venueName,
                            geometry: {
                              type: 'Point',
                              coordinates: [newItem.Lng, newItem.Lat],
                            },
                            properties: {
                              text: item.Name + '\n' + venueName,
                            },
                          });
                        }
                      });
                    });
                    // layer重新设置数据
                    compState.ambuLayer.setData(compState.layerdata);
                    console.log('重新设置了车辆标签图层！');
                  }
                }
              })
              .catch((err) => {
                console.log(err);
              });
          }, 8000);
          // ------------------------------------------------------------------end
          // 初始化城市下拉框和场馆下拉框 跳转------------------------------------start
          // console.log(ACVCodesVx.value)
          let { selectType } = ACVCodesVx.value;
          if (
            selectType == 'selectCity' &&
            cityInfoVx.value != null &&
            cityInfoVx.value?.Code != -1
          ) {
            await map.setCenter(cityInfoVx.value?.name);
          } else if (
            selectType == 'selectVenue' &&
            venueInfoVx.value != null &&
            venueInfoVx.value?.Code != -1
          ) {
            let LngLatObj = wgs84togcj02tobd09(
              venueInfoVx.value?.Lng,
              venueInfoVx.value?.Lat,
            );
            map.flyTo(new BMapGL.Point(LngLatObj.Lng, LngLatObj.Lat), 17);
          } else {
          }
          // ------------------------------------------------------------------end
        } catch (error) {
          console.log('homeMap', error);
        }
      });
    });
    onUnmounted(() => {
      clearInterval(compState.ambuTimer);
      // clearTimeout(compState.ambuTimer)
      compState.ambuTimer = null;
      console.log('homeMap/clear车辆循环刷新定时器！');
    });
    const refState = toRefs(compState);
    return {
      // 状态
      ...refState,
      map,
      medicalRooms,
      doctorsVx,
      nursesVx,
      ambulancesVx,
      // 事件
      InitMyMap,
      CreateMark,
      filterNode,
      // 医院
      handShowHospital,
      handleCloseHospital,
      handleHospitalNode,
      // 车辆
      handleShowAmbulance,
      handleCloseAmbulanceInfo,
      handleAmbulanceInfoNode,
      // 药品耗材
      handleSurplus,
      handleDrugNodeClick,
      closeDrugConsumClick,
      receiveDACRequestRes,
      // 医务室
      handleShowMedicalRoomPoint,
      handlemedicalRoomPointNodeClick,
      handleCloseMedicalRoomPoint,
      // 医生/护士
      handleShowUserInfo,
      handleUserInfoNodeClick,
      handleCloseUserInfo,
      // 图例
      handleShowWhichPar,
      // 地图右侧
      handleLinePosition,
      handleClearLine,
      // 显隐藏按钮
      handleShowLeft,
      handleHideAmbuTag,
      handleSendHospital,
      handleCloseSendHospital,
      handleAceptPatient,
      // handleCloseAcceptPatient
      handleOrdinaryPattern,
      handleDiurnalPattern,
      handleDarkPattern,
    };
  },
};
</script>
<style scoped>
.map {
  width: 100%;
  height: 100%;
  position: absolute;
  z-index: 0;
}

/* 地图左侧 */
.map_left {
  position: absolute;
  margin: 3px;
  z-index: 1;
}

/* 地图右侧 */
.map_right {
  width: 520px;
  position: absolute;
  right: 3px;
  margin-top: 3px;
}

.fk_home .custom_dialog {
  position: absolute;
  height: 500px;
  width: 300px;
  background: #fff;
  left: 310px;
  top: 65px;
  z-index: 9;
}

/* .fk_home .drug_venue_dialog {
  position: absolute;
  height: 300px;
  width: 220px;
  background: #fff;
  left: 260px;
  top: 400px;
} */

/* 地图图标显示窗口 */
:deep(.BMap_bubble_pop) {
  padding: 0 !important;
}

:deep(.BMap_bubble_top) {
  background: #758bfd !important;
}

:deep(.BMap_bubble_top .BMap_bubble_title) {
  margin-left: 5px !important;
}

/* // 去掉文字那行，添加CSS即可 */
:deep(.BMap_cpyCtrl) {
  display: none;
}

.fk_home .tree_icon {
  cursor: pointer;
  position: relative;
  margin: 5px;
}

.fk_home .tree_icon:hover {
  color: #758bfd;
}

.fk_home .patient-custom-dialog {
  position: absolute;
  right: 550px;
  top: 100px;
  background-color: #fff;
  width: 900px;
  border: 1px solid rgba(225, 225, 225, 0.5);
  z-index: 9;
}
</style>
